package com.itqf.shiro;

import com.itqf.bean.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * projectName: rbac2103
 *
 * @author: 赵伟风
 * time: 2021/7/9 14:48
 * description:
 */
public class AuthorizaticationDemo {


    public static void main(String[] args) {


        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请您输入输入账号!");
        String account = scanner.nextLine();
        System.out.println("请您输入输入密码!");
        String password = scanner.nextLine();

        UsernamePasswordToken token = new UsernamePasswordToken(account,password);

        try {
            subject.login(token);
            System.out.println("认证成功!");
        }catch (AuthenticationException e)
        {
            System.out.println("认证失败");
        }

        //认证通过以后,方可获取!
        User user = (User) subject.getPrincipal();
        System.out.println("principal = " + user);

        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);



        while (true)
        {
            System.out.println("请输入要检查的角色名!");
            String role = scanner.nextLine();
            boolean b = subject.hasRole(role);
            System.out.println("b = " + b);
            System.out.println("-------------");
            System.out.println("请输入要检查的权限!");
            String permission = scanner.nextLine();
            boolean permitted = subject.isPermitted(permission);
            System.out.println("permitted = " + permitted);

        }


       // subject.logout();

    }

}
